declare var wx;
import { _decorator, Component, Node } from 'cc';
import { Global } from '../Global';
const { ccclass, property } = _decorator;
type AdInfor = {
    Video: string[],
    Banner: string,
    Gird: string
}

@ccclass('WxAdMgr')
/**
 * 微信广告管理
 */
export class WxAdMgr {
    //激励视频广告
    private RewardVideos = {};

    //banner广告
    private Banner = null;

    //格子广告
    private Gird = null;

    //激励视频回调
    private VideoCb: Function = null;

    /**
     * 广告初始化
     */
    public Init(_adinfor: AdInfor) {
        //播放激励广告
        for (let id of _adinfor.Video) {
            let vidoad = wx.createRewardedVideoAd({ adUnitId: id });
            vidoad.onLoad(() => { Global.IsDebug && console.log("抖音广告加载成成功") })
            vidoad.onError((err) => { Global.IsDebug && console.log("抖音广告加载失败", err) })
            vidoad.onClose((res) => { this.VideoClose(res.isEnded) })
        }

        //如果有banner信息
        if (_adinfor.Banner) {
            this.Banner = wx.createBannerAd({
                adUnitId: _adinfor,
                adIntervals: 30,
                style: {
                    left: 0,
                    top: 0,
                    width: screen.width
                }
            })
            this.Banner.onResize((res) => {//banner广告适配,放到屏幕的最下方
                console.log(res)
                this.Banner.top = screen.height - res.height;
            })
        }

        //如果有格子广告
        if (_adinfor.Gird) {
            this.Gird = wx.createGridAd({
                adUnitId: _adinfor.Gird,
                adIntervals: 30,
                style: {
                    left: 0,
                    top: screen.height / 2 - 200,
                }
            })
        }

    }

    /**
     * 播放激励视频
     */
    public ShowVideo(_adid: string, _cb: Function) {
        this.VideoCb = _cb;
        this.RewardVideos[_adid].load().then(() => {
            this.RewardVideos[_adid].show().catch((err) => {
                Global.IsDebug && console.log("播放失败", err)
                this.VideoClose(false);
            });
        })
    }

    /**
     * 激励视频关闭
     */
    public VideoClose(_isend: boolean) {
        wx.showToast({
            title: _isend ? "领取成功" : "领取失败",
            icon: _isend ? "success" : "fail"
        })
        this.VideoCb && this.VideoCb(_isend);
    }

    /**
    * 显示banner广告
    * @param 是否显示
    */
    public ShowBannerAd(_isshow: boolean) {
        if (_isshow) {
            this.Banner.show();
        }
        else this.Banner.hide();
    }

    /**
    * 显示格子广告
    * @param 是否显示
    */
    public ShowGridAd(_isshow: boolean) {
        if (_isshow) {
            this.Gird.ad.show();
        }
        else this.Gird.ad.hide();
    }
}


